package com.demo.generate.code.command;

import com.demo.generate.code.service.CodeGeneratorService;
import com.demo.generate.code.service.TableInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.List;

/**
 * 代码生成命令行执行类
 */
@Component
public class GeneratorCommand implements CommandLineRunner {
    
    @Autowired
    private CodeGeneratorService codeGeneratorService;
    
    @Autowired
    private TableInfoService tableInfoService;
    
    @Override
    public void run(String... args) throws Exception {
        if (args.length < 1) {
            System.out.println("请指定要生成代码的表名");
            System.out.println("使用方法: java -jar generator.jar tableName [tableName2] ...");
            System.out.println("或者使用 'all' 生成所有表的代码");
            return;
        }
        
        try {
            if ("all".equalsIgnoreCase(args[0])) {
                // 生成所有表的代码
                List<String> tableNames = tableInfoService.getTableNames();
                System.out.println("发现 " + tableNames.size() + " 个表，开始生成代码...");
                
                for (String tableName : tableNames) {
                    System.out.println("正在生成表 [" + tableName + "] 的代码...");
                    generateCodeForTable(tableName);
                }
            } else {
                // 生成指定表的代码
                for (String tableName : args) {
                    System.out.println("正在生成表 [" + tableName + "] 的代码...");
                    generateCodeForTable(tableName);
                }
            }
            
            System.out.println("代码生成完成!");
        } catch (SQLException e) {
            System.err.println("数据库操作异常: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("代码生成异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 为指定表生成代码
     * 
     * @param tableName 表名
     */
    private void generateCodeForTable(String tableName) {
        try {
            codeGeneratorService.generateCode(tableName);
        } catch (Exception e) {
            System.err.println("生成表 [" + tableName + "] 的代码时发生异常: " + e.getMessage());
            e.printStackTrace();
        }
    }
}